<?php 
/**
*
* example目录下为简单的支付样例，仅能用于搭建快速体验微信支付使用
* 样例的作用仅限于指导如何使用sdk，在安全上面仅做了简单处理， 复制使用样例代码时请慎重
* 请勿直接直接使用样例对外提供服务
* 
**/
require_once "./lib/WxPay.Api.php";
require_once "./example/WxPay.JsApiPay.php";
require_once "./example/WxPay.Config.php";
require_once './example/log.php';

//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

//打印输出数组信息
function printf_info($data)
{
    foreach($data as $key=>$value){
        echo "<font color='#00ff55;'>$key</font> :  ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
    }
}

//①、获取用户openid
try{

	$tools = new JsApiPay();
	$openId = $tools->GetOpenid();
	
	$ono = "kcbjkq".date("YmdHis").mt_rand(100, 999);
	//②、统一下单
	$input = new WxPayUnifiedOrder();
	$input->SetBody("618活动");
	$input->SetAttach("618活动");
	$input->SetOut_trade_no($ono);
	$input->SetTotal_fee("1");
	$input->SetTime_start(date("YmdHis"));
	$input->SetTime_expire(date("YmdHis", time() + 600));
	$input->SetGoods_tag("test");
	$input->SetNotify_url("http://www.wgf001.top/work/wxpay/dsm_notify.php");
//	$input->SetNotify_url("http://www.wgf001.top/work/wxpay/call.php");
	$input->SetTrade_type("JSAPI");
	$input->SetOpenid($openId);
	$config = new WxPayConfig();
	$order = WxPayApi::unifiedOrder($config, $input);
	
	//可以在这里把下单信息写入数据库（未付款的订单信息）
	//$link = conn(...);...
	
	
	echo '<font color="#f00"><b>康承贝健618活动</b></font><br/>';
//	echo "openid:".$openId;
//	var_dump($openId);
//	printf_info($order);
	$jsApiParameters = $tools->GetJsApiParameters($order);

	//获取共享收货地址js函数参数
	$editAddress = $tools->GetEditAddressParameters();
} catch(Exception $e) {
	Log::ERROR(json_encode($e));
}
//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
/**
 * 注意：
 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
 */
?>

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/> 
    <title>康承贝健 - 618活动</title>
    <script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			<?php echo $jsApiParameters; ?>,
			function(res){
				WeixinJSBridge.log(res.err_msg);
//				alert(res.err_code+res.err_desc+res.err_msg);
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	</script>
	<script type="text/javascript">
	//获取共享地址
	function editAddress()
	{
		WeixinJSBridge.invoke(
			'editAddress',
			<?php echo $editAddress; ?>,
			function(res){
				var value1 = res.proviceFirstStageName;
				var value2 = res.addressCitySecondStageName;
				var value3 = res.addressCountiesThirdStageName;
				var value4 = res.addressDetailInfo;
				var tel = res.telNumber;
				
//				alert(value1 + value2 + value3 + value4 + ":" + tel);
			}
		);
	}
	
	window.onload = function(){
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', editAddress, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', editAddress); 
		        document.attachEvent('onWeixinJSBridgeReady', editAddress);
		    }
		}else{
			editAddress();
		}
	};
	
	</script>
</head>
<body>
   <br/>
	<div style="text-align: center;padding: 60px 0;">
	    <img style="width: 80%;height: auto;" src="dsm/7.png"/>
	</div>
	<p style="font-size: 40px; color: #337ab7;">618活动</p>
    <font color="#9ACD32"><b>该活动支付金额为<span style="color:#f00;font-size:50px">0.01</span>元钱</b></font><br/><br/>
	<div align="center">
		<button style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer;  color:white;  font-size:16px;" type="button" onclick="callpay()" >立即支付</button>
	</div>
	<!--<p id="pid"></p>-->
</body>
<script type="text/javascript">
function ajks(){
	var pid = document.getElementById('pid');
	var ajax = new XMLHttpRequest();ajax.open('get','orderquery_ajax.php?ono=<?php echo $ono;?>');ajax.send();
	ajax.onreadystatechange = function () {
		if (ajax.readyState==4 && ajax.status==200) {
			var state = JSON.parse(ajax.responseText);
//			pid.innerHTML = state;
			if(state == "SUCCESS"){
				//跳转指定页面
//				window.location.href='dsm/pay_success.html';
				//提示支付成功
				alert("支付成功！可以关闭页面了。");
				clearInterval(inter);
				//返回
				history.go(-1);
			}
			
		}
	}
}
var inter = setInterval(ajks,1000);
</script>
</html>